<template>
  <div class="exercise-content">
    <div class="exercise-body">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/?type=1' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/?type=1' }">科目{{ types == 1 ? '一' : '四' }}</el-breadcrumb-item>
        <!-- <el-breadcrumb-item :to="{ path: '/?type=1' }"
          >科目四</el-breadcrumb-item
        > -->
        <el-breadcrumb-item v-if="examType == 1" :to="backUrl">{{ "章节练习" }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="examType == 2" :to="backUrl">{{ "专题练习" }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="examType == 3" :to="backUrl">{{ "精选500" }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="examType == 4" :to="backUrl">{{ "三力测试" }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="examType == 5" :to="backUrl">{{ "顺序练习" }}</el-breadcrumb-item>
        <el-breadcrumb-item>试题练习</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="topic-body">
        <div class="topic-title">
          <div class="topic-type" v-if="topicInfo.type == 1">单选</div>
          <div class="topic-type" v-if="topicInfo.type == 2">多选</div>
          <div class="topic-type" v-if="topicInfo.type == 3">判断</div>
          <div class="topic-text">
            {{page + '、' +  topicInfo.title }}
            <span class="topic-btn" @click="playVoice">读题</span>
          </div>
        </div>
        <div v-if="topicInfo.full_image != null" style="margin-top: 10px;">
          <img :src="topicInfo.full_image" alt="">
        </div>
        <!-- 单选、判断 -->
        <div class="option-list" v-if="topicInfo.type == 1 || topicInfo.type == 3">
          <div class="option-item" v-for="(item, index) in topicInfo.options" :key="index"
						@click="radioGroupChange(item)">
            <img :src="item.noSelect" alt="" />
            <div>{{item.option + '.  ' + item.content}}</div>
          </div>
        </div>
        <!-- 多选 -->
        <div class="option-list" v-if="topicInfo.type == 2">
          <div class="option-item" v-for="(item, index) in topicInfo.options" :key="index"
						@click="checkGroupChange(item)">
            <img :src="item.noSelect" alt="" />
            <div>{{item.option + '.  ' + item.content}}</div>
          </div>
        </div>
        <!-- 用户选择出错 -->
        <div class="topic-tips" v-if="isError">
          <div>
            <span>正确答案</span>
            <span class="true-answer">{{isCorrect}}</span>
          </div>
          <div>
            <span>您的选择</span>
            <span class="wrong-answer">{{isSelect}}</span>
          </div>
        </div>
      </div>
      <div class="topic-analysis" v-show="isSelect != ''">
        <div class="analysis-title">技巧讲解</div>
        <div class="analysis-body">
          <div class="analysis-subTitle">
            <img src="@/assets/tmjx.png" alt="" />
            <div>题目解析</div>
          </div>
          <div class="analysis-text">
            {{topicInfo.official_parse}}
          </div>
        </div>
      </div>
      <div class="funcation-box">
        <div class="fun-left">
          <div class="change-btn" @click="backTopic">上一题</div>
          <div class="change-btn" @click="nextTopic">下一题</div>
          <div class="collect-topic" @click="addCollect(topicInfo)">
            <img src="@/assets/sc.png" alt="" />
            <div>收藏</div>
          </div>
        </div>
        <div class="fun-right">
          <div class="true-wrong">
            <img src="@/assets/组 16.png" alt="" />
            <div>{{ correctTotal }}</div>
          </div>
          <div class="true-wrong">
            <img src="@/assets/组 16(1).png" alt="" />
            <div>{{ errorTotal }}</div>
          </div>
          <div class="topic-fun" @click="listShow = !listShow">
            <img src="@/assets/1.png" alt="" />
            <div>{{ page }}/{{ topicTotal.length }}</div>
          </div>
        </div>
      </div>
      <div class="topic-list" v-if="listShow">
        <div class="scroll-box">
          <!-- 2 correct正确   3 error错误  1 default默认  current当前  -->
          <div :class="page==(item.subIndex)?'current':(item.isErr == 1?'default':(item.isErr == 2?'correct':'error'))" 
          class="topic-item" v-for="(item, index) in topicTotal" :key="index" @click="goTopic(index + 1)">{{ index + 1 }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 分类题目信息
import {
  getSortList,
  topicDetails,
  getChapters,
  getThreeTest,
  getWinnow500,
  getThisYear
} from '@/api/index.js'
// 添加收藏
import {
  addErrtopic,
  addCollect
} from '@/api/user.js';
// 课程购买信息
import { getPurchasedCourses } from '@/api/index.js'
export default {
  name: "ExamExercise",
  data() {
    return {
      examType: 0,
      backUrl: {
        path: "",
      },
      // 语音
      Audio: new SpeechSynthesisUtterance(),
      synth: window.speechSynthesis,// 启用文本
      topicInfo: {},
      topicType: 0, // 题目类型，5顺序练习 2专题练习 1章节练习 4三力测试 3精选500 6今年新题
      listShow: false,
      page: 1,
      types: 1,
      topicType: 1,
      isBuy: 0,
      isSelect: '',
      isCorrect: '',
      isError: false,
      isFirstClick: false,
      isrequest:true,
      tipsShow: false,
      topicTotal: [],
      correctTotal: 0,
      errorTotal: 0,
      correctImg: require('@/assets/组 16.png'),// 正确
      errorImg: require('@/assets/组 16(1).png'),// 错误
      noSelect: require('@/assets/椭圆 4241 拷贝.png'),// 没有选择
      typeId:0
    };
  },
  mounted() {
    this.handleExamType();
    // 科目
    this.types = this.$route.query.type
  },
  watch: {
    page: {
      handler(val,oldv) {
        if (val != oldv) {
          // 题目类型，5顺序练习 2专题练习 1章节练习 4三力测试 3精选500 6今年新题
          switch (this.examType) {
            case '1':
              this.getChapters();
              break;
            case '2':
            this.topicDetails();
              break;
            case '3':
              this.getWinnow500();
              break;
            case '4':
              this.getThreeTests();
              break;
            case '5':
              this.getSortList();
              break;
            case '6':
              this.getThisYear();
              break;
            default:
              break;
          }
        }
      },
      deep: true
    }
  },
  methods: {
    // 处理练习类型
    handleExamType() {
      this.examType = this.$route.query.topicType;

      // this.examType == 1
      //   ? (this.backUrl.path = "/ChapterExercise")
      //   : (this.backUrl.path = "/SpecialExercises");
      let that = this
      
      let id = this.$route.query.id;
      that.typeId = id
      // 章节练习
      if (this.examType == 1) {
        this.getChapters()
      }
      // 专题练习
      if (this.examType == 2) {
        this.topicDetails()
      }
      // 精选500
      if (this.examType == 3) { 
        this.getWinnow500()
      }
      // 三力测试
      if (this.examType == 4) { 
        this.getThreeTest()
      }
      // 顺序测试
      if (this.examType == 5) { 
        this.getSortList()
      }
      // 新题
      if (this.examType == 6) { 
        this.getThisYear()
      }
    },
    // 单选
    radioGroupChange(item) {
      let count = localStorage.getItem('question_count');
      count = parseInt(count)
      count += 1;
      localStorage.setItem('question_count', count);
      if (!this.isFirstClick) {
        this.isSelect = item.option; // 添加用户选项
        if (item.is_correct == 1) { // 选对
          this.correctTotal += 1;
          item["selected"] = this.correctImg;
          item.noSelect = item["selected"];
          // 添加到弹出层
          this.topicTotal[this.page - 1].isErr = 2;
          // this.nextTopic();//下一题
        } else { // 选错
          this.errorTotal += 1
          item["errorImg"] = this.errorImg;
          item.noSelect = item["errorImg"];
          // 添加到弹出层
          this.topicTotal[this.page - 1].isErr = 3;
          // 找出正确答案
          for (let s of this.topicInfo.options) {
            // console.log(55,s);
            if (s.is_correct == 1) {
              s["selected"] = this.correctImg;
              s.noSelect = s["selected"];
            }
          }
          // 添加错误选项
          let obj = {
            type: this.topicType,
            question_id: this.topicInfo.id,
            question_option_ids: [item.id]
          }
          this.addErrTopic(obj)
          let errnum = localStorage.getItem('question_error');
          count = parseInt(errnum)
          errnum += 1;
          localStorage.setItem('question_error',errnum);
        }
        this.isFirstClick = true;
      } else {
        return
      }
    },

    // 多选
    checkGroupChange(item) {
      let count = localStorage.getItem('question_count');
      count = parseInt(count)
      count += 1;
      localStorage.setItem('question_count', count);
      if (this.isSelect.indexOf(item.option) == -1) {
        this.isSelect += item.option + '、'; // 添加用户选项
      }
      if (item.is_correct == 1) { // 选对
        // this.correctTotal += 1;
        item["selected"] = this.correctImg;
        item.noSelect = item["selected"];
        // 添加到弹出层
        // this.topicTotal[this.page - 1].isErr = 2;
        // this.nextTopic();//下一题
      } else { // 选错
        this.errorTotal += 1;
        this.isError = true;
        item["errorImg"] = this.errorImg;
        item.noSelect = item["errorImg"];
        // 添加到弹出层
        this.topicTotal[this.page - 1].isErr = 3;
        // 找出正确答案
        for (let s of this.topicInfo.options) {
          // console.log(55,s);
          if (s.is_correct == 1) {
            s["selected"] = this.correctImg;
            s.noSelect = s["selected"];
          }
        }
        // 添加错误选项
        let obj = {
          type: this.topicType,
          question_id: this.topicInfo.id,
          question_option_ids: [item.id]
        }
        this.addErrTopic(obj)
        let errnum = localStorage.getItem('question_error');
        errnum = parseInt(errnum)
        errnum += 1;
        localStorage.setItem('question_error', errnum);
      }
      this.isFirstClick = true;
    },
    // payCourse购买课程
    payCourse() {
      this.$router.push('/GoodCourse')
    },
    // 语音读题播报
    playVoice() {
      // let u = new SpeechSynthesisUtterance();
      let str = this.topicInfo.title
      this.synth.cancel(str)
      this.Audio.text = str;
      this.Audio.lang = 'zh';
      //u.rate = 0.7
      speechSynthesis.speak(this.Audio);
    },
    // 添加错题
    addErrTopic(obj) {
      addErrtopic(obj).then(res => {
        // console.log(888, res);
      }).catch(err => {
        this.$message.error('错题添加失败！');
      })
    },
    // 添加收藏
    addCollect(item) {
      let obj = {
        type: this.topicType,
        question_id: item.id
      }
      addCollect(obj).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '收藏成功',
            type: 'success'
          });
        } else {
          // toast(res.message)
        }
      }).catch()
    },
    // 上一题
    backTopic() {
      // 多选
      if ((this.isSelect == this.isCorrect) && (this.topicInfo.type == 2) && this.isSelect != '') {
        this.correctTotal += 1;
        this.topicTotal[this.page - 1].isErr = 2;
      }
      if ((this.isSelect != this.isCorrect) && (this.topicInfo.type == 2) && this.isSelect != '') {
        this.topicTotal[this.page - 1].isErr = 3;
        // this.errorTotal += 1;
      }
      // 单休、判断
      if ((this.isSelect == this.isCorrect) && (this.topicInfo.type == 1 || this.topicInfo.type == 3) && this.isSelect != '') {
        this.correctTotal += 1;
        this.topicTotal[this.page - 1].isErr = 2;
      }
      if ((this.isSelect != this.isCorrect) && (this.topicInfo.type == 1 || this.topicInfo.type == 3) && this.isSelect != '') {
        this.topicTotal[this.page - 1].isErr = 3;
        // this.errorTotal += 1;
      }
      if (this.page == 1) {
        this.$message.error('已是第一题');
        return;
      } else {
        this.isFirstClick = false;
        this.isSelect = ''
        this.page -= 1;
        this.isError = false;
      }
    },
    // 下一题
    nextTopic() {
      // 多选
      if (((this.isSelect + '、') == this.isCorrect) && (this.topicInfo.type == 2) && this.isSelect != '') {
        this.correctTotal += 1;
        this.topicTotal[this.page - 1].isErr = 2;
      }
      if (((this.isSelect + '、') != this.isCorrect) && (this.topicInfo.type == 2) && this.isSelect != '') {
        this.topicTotal[this.page - 1].isErr = 3;
        // this.errorTotal += 1;
      }
      // 单休、判断
      if (((this.isSelect + '、') == this.isCorrect) && (this.topicInfo.type == 1 || this.topicInfo.type == 3) && this.isSelect != '') {
        this.correctTotal += 1;
        this.topicTotal[this.page - 1].isErr = 2;
      }
      if (((this.isSelect + '、') != this.isCorrect) && (this.topicInfo.type == 1 || this.topicInfo.type == 3) && this.isSelect != '') {
        this.topicTotal[this.page - 1].isErr = 3;
        // this.errorTotal += 1;
      }
      if (this.page < this.topicTotal.length) {
        this.isFirstClick = false;
        this.isSelect = '';
        this.isError = false;
        if (this.page >= 30 && (this.isBuy == 0)) {
          this.tipsOpen()
          return;
        } else {
          this.page += 1;
        }
      } else {
        this.$message.error('已是最后一题');
      }
    },
    // 购买课程弹窗提示
    tipsOpen(){
      let that = this
      this.$confirm('未付费学员（过客身份）有试用权限  试用 30 题', '提示', {
          confirmButtonText: '购买课程',
          cancelButtonText: '暂不购买',
          type: 'warning'
        }).then(() => {
          that.payCourse()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
    },
    // 跳转到某题
    goTopic(count) {
      if (count >= 30 && (this.isBuy == 0)) {
        this.tipsOpen()
        return;
      } else {
        this.page = count;
        this.topicShow = false;
      }
    },

    // 章节练习
    getChapters() {
      let that = this
      let obj = {
        limit: 1,
        page: this.page,
        subject: this.types
      }
      let id = that.typeId
      getChapters(id, obj).then(res => {
        if (res.list.length > 0) {
          that.topicInfo = res.list[0].question;
          if (that.isrequest) {
            // that.topicTotal = res.data.data.length;
            // 计算题目数量，并设置为默认未做
            let total = res.total;
            for (let i = 1; i <= total; i++) {
              let o = {
                isErr: 1,
                subIndex: i
              }
              that.topicTotal.push(o)
            }
            that.isrequest = false
          }
          // 添加正确选项
          that.isCorrect = ''
          that.topicInfo.options.map(item => {
            item["noSelect"] = that.noSelect;
            if (item.is_correct == 1) {
              that.isCorrect += item.option + '、';
            }
          })
          that.topicInfo = that.topicInfo;
        } else {
          that.topicTotal = []
          that.topicInfo = {}
        }
      })
    },
    // 专题练习
    topicDetails() {
      let that = this
      let obj = {
        limit: 1,
        page: this.page,
        subject: this.types
      }
      let id = that.typeId
      topicDetails(id, obj).then(res => {
        if (res.list.length > 0) {
          that.topicInfo = res.list[0].question;
          if (that.isrequest) {
            // that.topicTotal = res.data.data.length;
            // 计算题目数量，并设置为默认未做
            let total = res.total;
            for (let i = 1; i <= total; i++) {
              let o = {
                isErr: 1,
                subIndex: i
              }
              that.topicTotal.push(o)
            }
            that.isrequest = false
          }
          // 添加正确选项
          that.isCorrect = ''
          that.topicInfo.options.map(item => {
            item["noSelect"] = that.noSelect;
            if (item.is_correct == 1) {
              that.isCorrect += item.option + '、';
            }
          })
          that.topicInfo = that.topicInfo;
        } else {
          that.topicTotal = []
          that.topicInfo = {}
        }
      })
    },
    // 精选500
    getWinnow500() {
      let obj = {
        limit: 1,
        page: this.page,
        // subject: this.types
      }
      let that = this
      getWinnow500(obj).then(res => {
        if (res.list.length > 0) {
						that.topicInfo = res.list[0].question;
						if(that.isrequest){
							// 计算题目数量，并设置为默认未做
							let total = res.total;
							for (let i = 1; i <= total; i++) {
								let o = {
									isErr: 1,
									subIndex: i
								}
								that.topicTotal.push(o)
							}
							that.isrequest = false
						}
						// 添加正确选项
						that.isCorrect = ''
						that.topicInfo.options.map(item => {
							item["noSelect"] = that.noSelect;
							if (item.is_correct == 1) {
								that.isCorrect += item.option + '、';
							}
						})
						that.topicInfo = that.topicInfo;
					} else {
						that.topicTotal = []
						that.topicInfo = {}
					}
      })
    },
    // 三力测试
    getThreeTest() {
      let obj = {
        limit: 1,
        page: this.page,
        subject: this.types
      }
      let that = this
      getThreeTest(obj).then(res => {
        if (res.data.list.length > 0) {
						that.topicInfo = res.list[0];
						if(that.isrequest){
							// that.topicTotal = res.data.data.length;
							// 计算题目数量，并设置为默认未做
							let total = res.total;
							for (let i = 1; i <= total; i++) {
								let o = {
									isErr: 1,
									subIndex: i
								}
								that.topicTotal.push(o)
							}
							that.isrequest = false
						}
						// 添加正确选项
						that.isCorrect = ''
						that.topicInfo.options.map(item => {
							item["noSelect"] = that.noSelect;
							if (item.is_correct == 1) {
								that.isCorrect += item.option + '、';
							}
						})
						that.topicInfo = that.topicInfo;
					} else {
						that.topicTotal = []
						that.topicInfo = {}
					}
      })
    },
    // 顺序练习
    getSortList() {
      let obj = {
        limit: 1,
        page: this.page,
        subject: this.types
      }
      let that = this
      getSortList(obj).then(res => {
        console.log(333, res)
        // 计算题目数量，并设置为默认未做
					if (res.total > 0) {
						if(that.isrequest){
							let total = res.total;
							for (let i = 1; i <= total; i++) {
								let o = {
									isErr: 1,
									subIndex: i
								}
								that.topicTotal.push(o)
							}
							that.isrequest = false;
						}
						// 取数组的第一个
						that.topicInfo = res.list[0];
						// 添加正确选项
						that.isCorrect = ''
						that.topicInfo.options.map(item => {
							item["noSelect"] = that.noSelect;
							if (item.is_correct == 1) {
								that.isCorrect += item.option + '、';
								// that.nowSelect = item.option;
							}
						})
						that.topicInfo = that.topicInfo;
					} else {
						that.topicTotal = []
						that.topicInfo = {}
					}
      })
    },
    // 新题
    getThisYear() {
      let obj = {
        limit: 1,
        page: this.page,
        subject: this.types
      }
      let that = this
      getThisYear(obj).then(res => {
        // 计算题目数量，并设置为默认未做
					if (res.total > 0) {
						if(that.isrequest){
							let total = res.total;
							for (let i = 1; i <= total; i++) {
								let o = {
									isErr: 1,
									subIndex: i
								}
								that.topicTotal.push(o)
							}
							that.isrequest = false;
						}
						// 取数组的第一个
						that.topicInfo = res.list[0];
						// 添加正确选项
						that.isCorrect = ''
						that.topicInfo.options.map(item => {
							item["noSelect"] = that.noSelect;
							if (item.is_correct == 1) {
								that.isCorrect += item.option + '、';
							}
						})
						that.topicInfo = that.topicInfo;
					} else {
						that.topicTotal = []
						that.topicInfo = {}
					}
      })
    }
  },
};
</script>

<style lang="scss">
.exercise-body {
  font-size: 0.9vw;
  padding: 1.5% 12.5%;
  padding-bottom: 0;
  background-color: #fff;
  min-height: 86.2vh;
  height: auto;

  .topic-body {
    margin-top: 2vh;

    .topic-title {
      display: flex;
      align-items: center;
      position: relative;

      .topic-type {
        position: absolute;
        top: 0;
        left: 0;
        font-size: 0.8vw;
        padding: 0.2vh 0.5vw;
        color: #fff;
        background: linear-gradient(180deg, #66ccad, #2ac092);
        border-radius: 6px;
      }

      .topic-text {
        margin: 0 1vw 0 3vw;
        width: max-content;

        .topic-btn {
          color: #2ac092;
          background: #d7f5ec;
          border: 1px solid #8ae6ca;
          border-radius: 6px;
          padding: 0.2vh 0.5vw;
          font-size: 0.7vw;
          cursor: pointer;
        }
      }
    }

    .option-list {
      margin-top: 2vh;

      .option-item {
        display: flex;
        align-items: center;
        margin-top: 2vh;
        cursor: pointer;

        >img {
          width: 1vw;
          height: 2vh;
          margin-right: 0.5vw;
        }
      }
    }

    .topic-tips {
      margin-top: 2vh;
      padding: 1vh 1.5vw;
      display: flex;
      border-radius: 10px;
      background-color: #f5f5f5;

      >div>span {
        margin-right: 1vh;
      }

      .true-answer {
        color: #2ac092;
      }

      .wrong-answer {
        color: #ff6d6a;
      }
    }
  }
}

.topic-analysis {
  margin-top: 5vh;
  border-bottom: 1px solid #e6e6e6;

  .analysis-title {
    text-align: center;
    font-size: 1.1vw;
    font-weight: bold;
  }

  .analysis-body {
    margin-top: 1vh;
    padding-bottom: 20vh;

    .analysis-subTitle {
      display: flex;
      align-items: center;

      >img {
        width: 1vw;
        height: 1vw;
        margin-right: 0.5vw;
      }
    }

    .analysis-text {
      margin-top: 2vh;
      padding: 2vh 2vw;
      border: 1px solid #e6e6e6;
      border-radius: 10px;
    }
  }
}

.funcation-box {
  width: 75%;
  display: flex;
  justify-content: space-between;
  padding: 1.5vh 0;
  position: fixed;
  bottom: 30px;
  background-color: #fff;
  border-top: #E6E6E6 1px solid;

  .fun-left,
  .fun-right {
    display: flex;
    align-content: center;
  }

  .change-btn {
    cursor: pointer;
    padding: 0.5vh 1vw;
    height: max-content;
    border: 1px solid #e6e6e6;
    border-radius: 25px;
    margin-right: 0.5vw;
  }

  .collect-topic {
    cursor: pointer;
    display: flex;
    height: max-content;
    align-items: center;
    background: linear-gradient(180deg, #ffc37f, #ffa23b);
    border-radius: 25px;
    padding: 0.5vh 1vw;
    color: #fff;
  }

  .true-wrong {
    display: flex;
    align-items: center;
    margin-right: 5vw;
  }

  .topic-fun {
    cursor: pointer;
    display: flex;
    align-items: center;
  }

  img {
    width: 1vw;
    height: 2vh;
    margin-right: 0.3vw;
  }
}

.topic-list {
  height: 30vh;

  .scroll-box {
    padding-right: .6vw;
    overflow-y: auto;
    height: 30vh;
    display: flex;
    // justify-content: space-between;
    flex-wrap: wrap;

    .topic-item {
      margin: 8px 0 1.5vh .9vw;
      cursor: pointer;
      text-align: center;
      width: 1vw;
      height: 1vw;
      padding: .6vw;
      border-radius: 50%;
      // border: 1px solid;
      display: flex;
			align-items: center;
			justify-content: center;
    }


    .correct {
			background-color: #DEFCF3;
			color: #2AC092;
		}

		.error {
			background-color: #FFE1E0;
			color: #FF6D6A;
		}

		.default {
			border: 1px #D1D1D1 solid;
			color: #999;
			background-color: #fff;
		}

		.current {
			border: 1px #2AC092 solid !important;
			color: #999;
			background-color: #fff;
		}
  }
}
</style>